﻿using furion.blog.Domain.IRepositories;
using furion.blog.Domain.MySQL;
using furion.blog.Domain.Query.RequestLog;
using furion.blog.Domain.Shared;
using Furion.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace furion.blog.EntityFramework.Core.Repositories
{
    public class RequestLogRepository : BaseSqlSugarRepository<RequestLog>, IRequestLogRepository, ISingleton
    {
        public readonly ISqlSugarClient _db;

        public RequestLogRepository(ISqlSugarClient db)
        {
            this._db = db;
        }


        public async Task Save(List<RequestLog> data) {
            //await base.InsertRangeAsync(data);
            await base.AsInsertable(data).SplitTable().ExecuteCommandAsync();
        }

        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<RequestLog> Detail(string date,long id) {
            string tableName = "request_log_"+date;
            return await this._db.Queryable<RequestLog>(" select t.* from `"+tableName+"` t ")
                .Where(" t.logId=@logId ")
                .AddParameters(new SugarParameter("logId", id))
                .FirstAsync();
        }

        /// <summary>
        /// 分页查询(只能根据日期查询)
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PageVO> List(RequestLogListQuery query) {
            try
            {
                //string tableName = "request_log_" + query.Date.Replace("-", "");
                var (strWhere, sqlParams) = query.QueryParams();
                long startIndex = query.GetStartIndex();


                string countSql = query.GetCountSQL();

                string dataSql = query.GetDataSQL();

                long total = await this._db.Ado.GetLongAsync(countSql, sqlParams);
                var data = await this._db.Ado.GetDataTableAsync(dataSql, sqlParams);
                return new PageVO { Total = total, Records = data };
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }
            return new PageVO { Total = 0L, Records = null };
        }

    }
}
